# -*- coding:utf-8 -*-
# time: 2025/7/18 ♡  14:24
# author:张伟
from celery import Celery, Task
from flask import Flask
from flask_mail import Message
from exts import mail
import config


def celery_init_app(app: Flask) -> Celery:
    class FlaskTask(Task):
        def __call__(self, *args: object, **kwargs: object) -> object:
            with app.app_context():
                return self.run(*args, **kwargs)

    celery_app = Celery(app.name, task_cls=FlaskTask)
    celery_app.config_from_object("config")
    celery_app.set_default()
    app.extensions["celery"] = celery_app
    return celery_app


flask_app = Flask(__name__)
flask_app.config.from_object(config)
celery = celery_init_app(flask_app)
mail.init_app(flask_app)


# 发送邮件
@celery.task
def send_mail(subject, recipients, body):
    message = Message(subject=subject, recipients=recipients, body=body)
    try:
        mail.send(message)
        return {"code": 200, "msg": "发送成功"}
    except Exception as e:
        return {"code": 500, "msg": f"{e}"}

